﻿using AutoMapper;
using B.MES.Customer.Domain;
using B.MES.Customer.Domain.DTO;
using B.MES.Customer.Infrastructure.IRepository;
using CSRedis;
using Dm.filter.log;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace B.MES.Customer.Infrastructure.Repository
{
    /// <summary>
    /// Bom仓储层
    /// </summary>
    public class BOMRepository : BaseRepository<BomTab>, IBOMRepository
    {
        /// <summary>
        /// ISqlSugarClient 实例
        /// </summary>
        private readonly ISqlSugarClient _client;
        /// <summary>
        ///  AutoMapper 实例
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// RedisClient 实例
        /// </summary>
        private readonly RedisClient _redis;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db">ISqlSugarClient 实例</param>
        public BOMRepository(ISqlSugarClient db, IMapper mapper) : base(db)
        {
            _client = db;
            _mapper = mapper;
            _redis = new RedisClient("10.31.59.13");
        }
        /// <summary>
        /// 添加 BOM 信息方法
        /// </summary>
        /// <param name="bom">参数 bomInfo: 要添加的 BOM 信息对象</param>
        public int AddBom(BOMDto bom)
        {
            //雪花ID
            //bom.BOMNum = YitIdHelper.NextId().ToString();
            var bomEntity = _mapper.Map<BomTab>(bom); // 使用 AutoMapper 进行映射
            bomEntity.Quantity = bom.Quantity ?? 1;
            bomEntity.ParentProductId=bom.ParentProductId?? 1;
            bomEntity.ChildProductId = bom.ChildProductId?? 1;
            return  _client.Insertable(bomEntity).ExecuteCommand();
        }
        /// <summary>
        /// 绑定成品类型
        /// </summary>
        /// <returns>成品类型列表</returns>
        public List<ArtifactType> GetArtifacTypeList()
        {
            string redisKey = "ArtifactTypeList";

            // 尝试从 Redis 中获取数据
            string serializedList = _redis.Get(redisKey);
            List<ArtifactType> list = null;

            if (!string.IsNullOrEmpty(serializedList))
            {
                // 如果 Redis 中存在数据，直接反序列化返回
                list = JsonConvert.DeserializeObject<List<ArtifactType>>(serializedList);
            }
            else
            {
                // 如果 Redis 中不存在数据，从数据库中查询
                list = _client.Queryable<ArtifactType>().ToList();

                // 序列化成 JSON 字符串，存入 Redis
                string json = JsonConvert.SerializeObject(list);
                _redis.Set(redisKey, json);
            }

            return list;
            //return _client.Queryable<ArtifactType>().ToList();
        }

        /// <summary>
        /// 显示、分页、查询Bom列表
        /// </summary>
        /// <param name="bomTopic">Bom主题</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <returns>Bom列表信息</returns>
        public PageApiResut<BomTab> GetBom(string? bomTopic, int pageIndex, int pageSize)
        {
            // 首先应用过滤条件，然后进行排序  
            var query = _client
                .Queryable<BomTab>()
                .WhereIF(!string.IsNullOrEmpty(bomTopic), x => x.BOMTopic.Contains(bomTopic))
                .OrderByDescending(x => x.BOMID);

            // 计算应用过滤和排序后的总记录数  
            var totalCount = query.Count();

            // 然后进行分页  
            var pageData = query
                .ToPageList(pageSize, pageIndex)
                .ToList();

            // 构造分页查询结果对象并返回  
            var result = new PageApiResut<BomTab>
            {
                TotalCount = totalCount,
                Data = pageData
            };
            return result;
        }
        /// <summary>
        /// 编辑Bom信息
        /// </summary>
        /// <param name="bomId">bom表主键</param>
        /// <returns>返回Bom实体</returns>
        public BomTab GetBomTabById(int bomId)
        {
            // 根据主键查询实体信息
            var bomTab = _client.Queryable<BomTab>().InSingle(bomId);
            return bomTab;
        }
        /// <summary>
        /// 修改Bom信息
        /// </summary>
        /// <param name="bom">要添加的 BOM 信息对象</param>
        /// <returns> 受影响行数</returns>
        public int UpdBomInfoById(BomTab bom)
        {
            //雪花ID
            //bom.BOMNum = YitIdHelper.NextId().ToString();
            bom.Quantity = bom.Quantity ?? 1;
            bom.ParentProductId = bom.ParentProductId ?? 1;
            bom.ChildProductId = bom.ChildProductId ?? 1;
            return _client.Updateable(bom).ExecuteCommand();
        }
        /// <summary>
        /// 获取Bom详情
        /// </summary>
        /// <param name="bomId">bom表主键</param>
        /// <returns> 获取Bom详情</returns>
        public APIResult<BOMDto> GetBomDetail(int bomId)
        {
            APIResult<BOMDto> aPIResult = new APIResult<BOMDto>();
            // 使用 SqlSugar 查询数据
            var bom = _client.Queryable<BomTab>().Where(t => t.BOMID == bomId).First();

            if (bom != null)
            {
                aPIResult.Data= new BOMDto
                {
                    BOMID = bom.BOMID,
                    BOMNum = bom.BOMNum,
                    BOMTopic = bom.BOMTopic,
                    Versions = bom.Versions,
                    ArtifactType = bom.ArtifactType,
                    DailyOutput = bom.DailyOutput,
                    ArtifactName = bom.ArtifactName,
                    Remark = bom.Remark,
                    Quantity = bom.Quantity,
                };
                return aPIResult;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 显示Bom列表
        /// </summary>
        /// <returns>Bom列表信息</returns>
        public List<BomTab> GetBomList()
        {
            var query1 = _client
           .Queryable<BomTab>().ToList();
            return query1;
        }
        /// <summary>
        /// 单个删除Bom信息
        /// </summary>
        /// <param name="bomId">BomId</param>
        /// <returns>受影响行数</returns>
        public int DelBomById(int bomId)
        {
            int n = _client.Deleteable<BomTab>().In(bomId).ExecuteCommand();
            return n;
        }
        /// <summary>
        /// 获取BOM下的物料信息
        /// </summary>
        /// <param name="bomId"> BomId</param>
        /// <returns> 物料信息</returns>
        public PageApiResut<Material> GetMaterialsByBOMId(int bomId)
        {
            PageApiResut<Material> pageApiResut = new PageApiResut<Material>();
            // 使用 SqlSugar 查询物料信息
            List<Material> materials = _client.Queryable<Material, BomTab>((m, b) => new object[]
            {
            JoinType.Inner, m.MatId == b.ChildProductId // 这里是根据外键关联 BOM 表和物料表
            })
            .Where((m, b) => b.BOMID == bomId)
            .Select((m, b) => m)
            .ToList();

            pageApiResut.Data = materials;
            return pageApiResut;
        }
    }
}
